import requests
import socket
from flask import Flask, jsonify, request
import os
import json
import random
import ConstructAPIResponse
import logging
from logging.handlers import SysLogHandler

FORMAT = '%(asctime)-15s [%(filename)s:%(lineno)d] -- %(message)s'
logging.basicConfig(filename='collectpvs.log',level=logging.DEBUG,format=FORMAT)
logging.getLogger('').addHandler(logging.StreamHandler())

requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.DEBUG)

from bs4 import BeautifulSoup


## Methods to make the PVS API Requests work
def requestPVS(method, params):
	params['key'] = '2cea7e95bdfbbc6551a0c56b10128165'
	r = requests.get('http://api.votesmart.org/' + method, params=params)
	#print r.url
	return BeautifulSoup(r.text, 'xml')

# Method to ping PVS API for a candidate ID
def getOfficialByZip(zip5, zip4):
	soup = requestPVS('Officials.getByZip', {'zip5': zip5, 'zip4': zip4})
	for candidate in soup.find_all('candidate'):
		if candidate.officeId.text == '5':
			return candidate.candidateId.text


app = Flask(__name__)

@app.route('/getMC', methods=['GET'])
def getMC():
	try:
		logging.info('Received request with info: ' + str(request.args))

		# Example url: http://0.0.0.0/getMC?zip5=94114&zip4=1675
		zip5 = request.args.get('zip5')#.strip()
		zip4 = request.args.get('zip4')#.strip()
		logging.info('Provided zip %s-%s', zip5, zip4)

		candidate_id = getOfficialByZip(zip5, zip4)
		logging.info('Found candidate id %s.', candidate_id)
		assert candidate_id, 'No candidate id found. Invalid zip code? (Or no current MC.)'

		assert int(candidate_id) != 123390, 'Curtis just elected and has no votes or ratings.'

		result = ConstructAPIResponse.tryBothSurveyAPIResponse(candidate_id)
		logging.info('API response returned to server for %s.', result['shortname'])
	except Exception as e:
		logging.error('Failed because %s.', str(e))
		result = {'success': 'FALSE'}

	return json.dumps(result, sort_keys=True)


if __name__ == '__main__':
	port = int(os.environ.get("PORT", 80))
	app.run(host='0.0.0.0', port=port, debug=True, threaded=True)